from time import sleep

from pandas import DataFrame

from data_tread import get_data_dict_list_mean

from config import ProjectInfo, Product, Sensor
from sensor_analyze import get_sensor_data
from sensor_db_sqlite import update_product, insert_product, insert_sensor, update_sensor, SQLStr, get_insert_str, \
    tread_many_row, db_conn_list
from sensor_upd import send_broadcast_for_sensor, get_sensor_raw_data


def search_sensor(broadcast_count=10):
    """
    向传感器发送广播
    :return: sensor_data_list 获取传感器的数据列表(数据信息为字典)
    """
    send_broadcast_for_sensor()
    for i in range(broadcast_count):
        send_broadcast_for_sensor()
        sleep(0.3)


# 获取传感器的数据
def receive_data_to_queue():
    """
    将传感器的数据解析后放入sensor_data_queue队列中
    若记录数据：将原始数据放入sensor_raw_data_queue 队列中
    """
    ProjectInfo.Sensor_data_Send_state = True
    while ProjectInfo.Sensor_data_Send_state:
        raw_data = get_sensor_raw_data()
        if raw_data:
            if ProjectInfo.Sensor_data_Record_state:
                ProjectInfo.sensor_raw_data_queue.put(raw_data)
            sensor_data = get_sensor_data(raw_data, data_type='dict')
            if sensor_data:
                ProjectInfo.sensor_data_queue.put(sensor_data)


# 计算传感器数据的平均值
def get_sensor_data_to_mean(data_count_per_sensor=5):
    """
    计算传感器数据的平均值，放入sensor_data_mean_queue队列中
    若记录数据放入sensor_recorded_data_queue中
    """
    data_list = []
    sensor_count = len(ProjectInfo.sensor_code_list)
    if sensor_count == 0:
        sensor_count = 1
    data_count = sensor_count * data_count_per_sensor
    while ProjectInfo.Sensor_data_Send_state:
        data = ProjectInfo.sensor_data_queue.get()
        if len(data_list) <= data_count:
            data_list.append(data)
        else:
            df_data_mean = get_data_dict_list_mean(data_list)
            ProjectInfo.sensor_data_mean_queue.put(df_data_mean)
            if ProjectInfo.Sensor_data_Record_state:
                ProjectInfo.sensor_recorded_data_queue.put(df_data_mean)
            data_list.clear()


# region 数据库操作

def update_product_to_db(product: Product):
    update_product(product.id, product.name, product.label)


def insert_product_to_db(product: Product):
    data_id = insert_product(product.name, product.label)
    product.id = data_id


def insert_sensor_to_db(sensor: Sensor):
    data_id = insert_sensor(sensor.sensor_code, sensor.location, sensor.direction, sensor.product_id)
    sensor.id = data_id


def update_sensor_to_db(sensor: Sensor):
    update_sensor(sensor.id, sensor.location, sensor.direction, sensor.product_id)


# 插入平均数据
def insert_sensor_data_to_db():
    """
    将平均值插入到数据库
    """
    while ProjectInfo.Sensor_data_Record_state:
        df: DataFrame = ProjectInfo.sensor_data_mean_queue.get()
        if type(df) is not DataFrame:
            break
        df['product_id'] = ProjectInfo.product.id
        df['d_time'] = df['d_time'].dt.strftime('%Y-%m-%d %H:%M:%S')
        if not SQLStr.Insert_Mean_Str:
            SQLStr.Insert_Mean_Str = get_insert_str('data', df.columns.tolist())
        data_list = df.values.tolist()
        tread_many_row(SQLStr.Insert_Mean_Str, data_list, db_conn_list[2])


# 插入原始数据
def insert_raw_data_to_db():
    """
    将原始数据插入到数据库
    """
    data_list = []
    product_id = ProjectInfo.product.id
    while ProjectInfo.Sensor_data_Record_state:
        raw_str = ProjectInfo.sensor_raw_data_queue.get()
        if not raw_str:
            continue
        if len(data_list) > 127:
            tread_many_row(SQLStr.Insert_Raw_Str, data_list, db_conn_list[3])
        else:
            data_list.append((raw_str, product_id))

# endregion
